import React, { useState, useEffect, useCallback } from 'react';
import { Space, Button, Table, Modal, message, Drawer, Form, Input } from 'antd';
import './style.scss';
import Search from 'antd/lib/input/Search';
import { BasicClassInfo, EntriesItem } from 'admin/schema/BasicWord';
import { ColumnsType } from 'antd/es/table/interface';
import {
  getWordList,
  createWordClass,
  modifyWordClass,
  deleteWordClass,
} from 'admin/servers/servers';
import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';
import { deleteRowChangePageNum } from 'utils/tools';

interface EntriesInfo {
  key: number;
  entriesName: string;
}

const SynonymWord: React.FC<{ versionId: number }> = props => {
  const [form] = useForm();
  const { versionId } = props;
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [wordList, setWordList] = useState<BasicClassInfo[]>([]);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');

  // 删除词类：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除词类：词类ID
  const [deleteWordClassId, setDeleteWordClassId] = useState<number>(0);
  // 删除词类：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);

  // 词类操作类型 0-新增 1-编辑
  const [actionType, setActionType] = useState<0 | 1>(0);

  // 编辑词类：词类ID
  const [modifyWordClassId, setModifyWordClassId] = useState<number>(0);

  // 新增/编辑词类：抽屉弹框显示
  const [createVisible, setCreateVisible] = useState<boolean>(false);

  // 新增/编辑词类：确认按钮loading
  const [confirmCreateLoading, setConfirmCreateLoading] = useState<boolean>(false);
  // 新建词条列表初始化数据
  const initialEntries = [
    {
      key: 0,
      entriesName: '',
    },
    {
      key: 1,
      entriesName: '',
    },
    { key: 2, entriesName: '' },
  ];

  // 词条列表,默认展示3个词条
  const [entries, setEntries] = useState<EntriesInfo[]>(initialEntries);
  // 词条数量
  const [entriesCount, setEntriesCount] = useState<number>(3);

  // 词类每列配置
  const columns: ColumnsType<BasicClassInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    {
      title: '词类名',
      dataIndex: 'wordClassName',
      key: 'wordClassName',
    },
    {
      title: '词条',
      dataIndex: 'entries',
      key: 'entries',
      render(arr) {
        if (!arr || !arr.length) return '';
        return arr
          .map((item: EntriesItem) => {
            return item.entriesName;
          })
          .join('|');
      },
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              modifyWordClassAction(index);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => {
              deleteWordClassAction(index);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  // 词条列表每列配置
  const columnsEntries: ColumnsType<EntriesInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1,
    },
    {
      title: <div>词条名</div>,
      dataIndex: 'entriesName',
      key: 'entriesName',
      render: (text, record, index) => (
        <Form.Item
          key={record.key}
          initialValue=""
          // name={`tableDt[${index}].entriesName`}
          name={['entries', index, 'entriesName']}
          style={{ marginBottom: 0 }}
          rules={[
            {
              whitespace: true,
              max: 20,
              message: '请输入20位以内字符',
            },
          ]}
        >
          <Input placeholder="请输入20位以内字符" maxLength={20} />
        </Form.Item>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              deleteEntriesAction(record.key);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  /**
   * Table数据加载
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getWordList({
        pageNo: current,
        pageSize: pageSize,
        wordClassType: 0,
        wordClassName: searchText,
        versionId,
      });
      if (res.code === 0) {
        setWordList(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('initData -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, searchText, versionId]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  /**
   * 根据词类名称搜索
   * @param text 搜索内容
   */
  const searchWordClass = (text: string) => {
    text = text.trim();
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };

  /**
   * 编辑操作
   * @param idx 所编辑数据的index
   */
  const modifyWordClassAction = (idx: number) => {
    console.log('编辑', idx);
    console.log(wordList[idx]);

    // eslint-disable-next-line prefer-const
    let { wordClassId, wordClassName, entries: entriesOrigin } = wordList[idx];

    if (!entriesOrigin) {
      entriesOrigin = initialEntries;
    }
    const entries = entriesOrigin.map((item, index) => {
      return {
        key: index,
        ...item,
      };
    });
    console.log(entries);

    setActionType(1);
    setModifyWordClassId(wordClassId);
    setEntries(entries);
    setEntriesCount(entries.length);
    setCreateVisible(true);
    form.setFieldsValue({
      wordClassName,
      entries,
    });
  };

  /**
   * 删除操作
   * @param idx 所删除数据的index
   */
  const deleteWordClassAction = (idx: number) => {
    console.log('删除', idx);
    setDeleteWordClassId(wordList[idx].wordClassId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除词类接口
   * @param wordClassId
   */
  const requestDeleteWordClass = async (wordClassId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteWordClass({
        wordClassId,
      });
      if (res.code === 0) {
        message.success('删除词类成功');
        deleteFresh(1);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('deleteWordClass -> res', res);
    } catch (error) {
      console.warn(error);
    }
    setDeleteVisible(false);
    setConfirmDeleteLoading(false);
  };

  /**
   * 确认
   */
  const onFinish = async (values: Store) => {
    console.log('onFinish -> values', values);

    const filterEntries = entries.filter(item => item.entriesName);

    // if (!filterEntries.length) {
    //   message.warning("至少新建一个词条！");
    //   return;
    // }
    setConfirmCreateLoading(true);

    if (actionType === 0) {
      // 新建词类
      requestCreateWordClass(values.wordClassName, filterEntries);
    } else if (actionType === 1) {
      // 编辑词类
      requestModifyWordClass(values.wordClassName, filterEntries);
    }

    setConfirmCreateLoading(false);
  };

  /**
   * 请求新增词类接口
   *
   */
  const requestCreateWordClass = async (wordClassName: string, entries: EntriesInfo[]) => {
    try {
      const res = await createWordClass({
        wordClassType: 0,
        versionId,
        wordClassName: wordClassName.trim(),
        entries,
      });
      if (res.code === 0) {
        // 成功
        message.success(`创建成功`);
        form.resetFields();
        setCreateVisible(false);
        refreshTable(1);
      } else {
        // 失败
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 请求编辑词类接口
   *
   */
  const requestModifyWordClass = async (wordClassName: string, entries: EntriesInfo[]) => {
    try {
      const res = await modifyWordClass({
        wordClassId: modifyWordClassId,
        wordClassName: wordClassName.trim(),
        entries,
      });
      if (res.code === 0) {
        // 成功
        message.success(`编辑成功`);
        form.resetFields();
        setCreateVisible(false);
        refreshTable();
      } else {
        // 失败
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 关闭抽屉弹框
   */
  const closeDrawer = () => {
    form.resetFields();
    setCreateVisible(false);
  };

  /**
   * 新建词条
   */
  const handleAdd = () => {
    const newData = {
      key: entriesCount,
      entriesName: '',
    };

    setEntries([...entries, newData]);
    setEntriesCount(entriesCount + 1);
    form.setFieldsValue({
      entries: [...entries, newData],
    });
  };
  /**
   * 删除词条
   */
  const deleteEntriesAction = (key: number) => {
    console.log('删除词条-key：', key);
    console.log(entries);
    const test = entries.filter(item => item.key !== key);
    console.log(test);
    setEntries(test);
    form.setFieldsValue({
      entries: test,
    });
  };
  /**
   * 抽屉弹框内容变更
   * @param changedValues 更改内容
   * @param allValues 表单所有内容
   */
  const onValuesChange = (changedValues: any, allValues: any) => {
    console.log(allValues);
    if (allValues.entries) {
      const res = allValues.entries.map((item: { entriesName: string }, index: number) => {
        return {
          key: index,
          ...item,
        };
      });
      setEntries(res);
    }
  };

  // 分页配置
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };

  return (
    <>
      <div className="basic-word-library-top">
        <Search
          placeholder="请输入词类名"
          enterButton="搜索"
          style={{ width: 300 }}
          onSearch={searchWordClass}
        />
        <div>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setActionType(0);
                setEntries(initialEntries);
                setEntriesCount(initialEntries.length);
                setCreateVisible(true);
                form.setFieldsValue({
                  wordClassName: '',
                  entries: initialEntries,
                });
              }}
            >
              新建同义词
            </Button>
          </Space>
        </div>
      </div>
      <div style={{ marginTop: 20 }} className="mgr-table">
        <Table
          loading={tableLoading}
          columns={columns}
          dataSource={wordList}
          rowKey="wordClassId"
          pagination={pagination}
        />
      </div>

      {/* 删除词类弹框 */}
      <Modal
        title="删除词类提示"
        visible={deleteVisible}
        onOk={() => {
          requestDeleteWordClass(deleteWordClassId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>

      <Drawer
        title={actionType === 0 ? '新建同义词' : '编辑同义词'}
        placement="right"
        getContainer={false}
        width={720}
        closable={false}
        onClose={closeDrawer}
        visible={createVisible}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={closeDrawer} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={() => form.submit()} type="primary" loading={confirmCreateLoading}>
              确定
            </Button>
          </div>
        }
      >
        <Form layout="horizontal" form={form} onFinish={onFinish} onValuesChange={onValuesChange}>
          <Form.Item
            label="同义词名"
            labelAlign="left"
            name="wordClassName"
            rules={[
              {
                required: true,
                whitespace: true,
                max: 20,
                message: '请输入20位以内字符',
              },
            ]}
          >
            <Input placeholder="请输入20位以内字符" maxLength={20} />
          </Form.Item>
          <Form.Item>
            <Space size="middle" style={{ marginTop: 20, marginBottom: 16 }}>
              <Button type="text" style={{ padding: 0 }}>
                词条列表
              </Button>
              <Button onClick={handleAdd} type="primary">
                新建词条
              </Button>
            </Space>

            <Table bordered dataSource={entries} columns={columnsEntries} pagination={false} />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default SynonymWord;
